<?php
/**
 * CRMLite Announce Controller
 *
 * @final
 * @package Crmlite_App
 * @version $Id: AnnounceController.php 37 2007-09-01 03:11:34Z etng2004 $
 * @copyright 2006-2007 ETE.CN
 * @author Yi BO  <etng2004@gmail.com>
 * @license PHP Version 3.0 {@link http://www.php.net/license/3_0.txt}
 */
require_once dirname(__FILE__) . '/BaseController.php';
final class AnnounceController extends BaseController
{
	public function indexAction()
	{
		$this->log('Annouce Index page called!');
		$this->_forward('list');
	}

	protected function getLatestAnnounce($count = 20)
	{
		$AM = new AnnounceModel();
		$where = array(
		'expired_at = 0 OR DATE(FROM_UNIXTIME(expired_at)) >= CURDATE()',
		'published_at = 0 OR DATE(FROM_UNIXTIME(published_at)) <= CURDATE()',
		);
		$order = 'created_at DESC';
		return $AM->findAll($where, $order, $count);
	}

	public function listAction()
	{
		$AM = new AnnounceModel();
		$where = array(
		'expired_at = 0 OR DATE(FROM_UNIXTIME(expired_at)) >= CURDATE()',
		'published_at = 0 OR DATE(FROM_UNIXTIME(published_at)) <= CURDATE()',
		);
		$order = 'created_at DESC';
		$pager = array(
		'curpage' 	=> $this->_getParam('page', 1),
		'perpage'	=> $this->_getParam('perpage', 10),
		'total'		=> $AM->count($where),
		'url'		=> $this->base_url . '/list',
		);
		$this->view->pager = $pager;
		$this->view->announces = $AM->paginate($where, $order, $pager['curpage'], $pager['perpage']);
	}

	public function viewAction()
	{
		$id = intval($this->_getParam('id', 1));
		$AM = new AnnounceModel();
		$this->view->announce = $AM->find($id);
	}
	/**
	 * 输出公告订阅种子，缓存方式为缓存数据
	 *
	 * @param string $default_feed_type
	 */
	public function feedAction($default_feed_type = 'rss')
	{
		/**
    	 * WE do not need render from template!
    	 */
    	$this->_helper->viewRenderer->setNoRender();

		$Cache = Zend_Registry::get('cache');
		/* @var $Cache Zend_Cache_Core */
		$feed_type = strval($this->_getParam('type'));
		in_array($feed_type, array('rss', 'atom')) || $feed_type = $default_feed_type;

		$cache_id = "announce_feed_data";
		if(!($feed_data = $Cache->load($cache_id)))
		{
			$config = Zend_Registry::get('config');
			$abs_base_url = $config->site->hostname . $this->base_url;
			$feed_data = array(
				'title'		=> $config->site->title,
				'link'		=> $abs_base_url .'/feed/',
				'charset'	=> 'utf-8',
				'entries'	=> array()
				);
			foreach ($this->getLatestAnnounce() as $entry)
			{
				$feed_data['entries'][] = array(
				'title'			=> $entry['title'],
				'link'			=> $abs_base_url . '/view/id/' . $entry['id'],
				'description'	=> $entry['content'],
				'pubdate'		=> $entry['created_at'],
				);
			}
			$this->log("Announce Feed Data created and cached!");
			$Cache->save($feed_data, $cache_id);
		}
		$feed = Zend_Feed::importArray($feed_data, $feed_type);
		/* @var $feed Zend_Feed_Abstract */
		$feed->send();
	}
}